import axios from "axios";
import { Notification, Loading } from "element-ui";
import store from "@/store";
import router from "@/router";
import {
  TIME_OUT_TIME,
  STATUS_CODE_OK,
  NOTIFY_STAY_TIME,
  HEADER_TOKEN_NAME,
} from "@/config";

let loadingInstace = null;
const fetch = axios.create({
  baseURL: process.env.VUE_APP_API_PROXY_URL,
  withCredentials: true,
  timeout: TIME_OUT_TIME,
});
// Access-Control-Allow-Origin
// 如果后端需要带cookie过去，前端需要设置为true
// withCredentials:默认情况下，跨源请求不提供凭据(cookie、HTTP认证及客户端SSL证明等)。通过将withCredentials属性设置为true，可以指定某个请求应该发送凭据。
// true：在跨域请求时，会携带用户凭证
// false：在跨域请求时，不会携带用户凭证；返回的 response 里也会忽略 cookie
// 当配置了 withCredentials = true时，必须在后端增加 response 头信息Access-Control-Allow-Origin，且必须指定域名，而不能指定为*
fetch.defaults.withCredentials = false;

// request拦截器
fetch.interceptors.request.use(
  (config) => {
    if (config.loading) {
      loadingInstace = Loading.service({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    }
    if (store.getters.token) {
      config.headers[HEADER_TOKEN_NAME] = store.getters.token;
    }
    store.dispatch("setLoading", true);
    return config;
  },
  (error) => {
    loadingInstace && loadingInstace.close();
    Notification.error({
      title: "错误",
      message: "请求失败!",
      duration: NOTIFY_STAY_TIME,
    });
    return Promise.reject(error);
  }
);
// respone拦截器
fetch.interceptors.response.use(
  (res) => {
    loadingInstace && loadingInstace.close();
    setTimeout(() => {
      store.dispatch("setLoading", false);
    }, 200);
    if (res.headers.uuid) {
      // 登录时需要传给后端uuid
      sessionStorage.setItem("uuid", JSON.stringify(res.headers.uuid));
    }
    // if (res.data.code == 40000) {
    //   router.push("/questionbank/continue");
    //   return false;
    // }
    if (res.data.msg && res.data.code != STATUS_CODE_OK) {
      Notification.error({
        title: "提示",
        message: res.data.msg,
        duration: NOTIFY_STAY_TIME,
      });
      if (res.data.code == 401001) {
        router.push("/login");
      }
    }
    return res;
  },
  (err) => {
    console.log(err, "err");
    loadingInstace && loadingInstace.close();
    setTimeout(() => {
      store.dispatch("setLoading", false);
    }, 200);
    Notification.error({
      title: "错误",
      message: "请求失败!",
      duration: NOTIFY_STAY_TIME,
    });
    return Promise.reject(err);
  }
);
export default fetch;
